// messageRouter.js
const { queryAllKeyWord } = require("./service/KeywordService")
const { sendPrivateMessageToUser } = require("./telegramAuth")
const { insertMsgRecord } = require("./service/MessageSendingRecord")
const channelListenerMap = new Map();

function registerHandler(channelId, handler) {
  console.log(channelId)
  console.log(handler)
  channelListenerMap.set(channelId.toString(), handler);
}

function unregisterHandler(channelId) {
  channelListenerMap.delete(channelId.toString());
}

function getHandler(channelId) {
  return channelListenerMap.get(channelId.toString());
}

/**
 * 发送私聊消息到用户账号
 * @param {*} msg 信息
 * @param {*} userId 用户ID
 * @param {*} accessHash 用户哈希值
 * @param {*} title 群聊名称
 * @param {*} groupId 群聊Id 
 * @param {*} client 链接的客户端 
 */
async function messageSnedUserHandler(msg, userId, accessHash, title, groupId, client) {

  let keywrods = await queryAllKeyWord()
  // console.log(keywrods)
  if (keywrods == "") {
    return
  }

  // let tets = []
  keywrods.forEach(async (itme, index) => {
    // console.log(itme)
    if (msg.includes(itme.key_wrod)) {
      // console.log("匹配====》",itme.key_wrod)
      await messageSnedUser(itme.content, userId, accessHash, title, msg, groupId,client)
    }
  })


}
/**
 * 发送私聊消息到用户
 * @param {*} msg 消息
 * @param {*} userId 用户ID
 * @param {*} accessHash 用户哈希值
 * @param {*} title 群聊名称
 * @param {*} olmsg 私信关键词  
 * @param {*} groupId 群聊Id 
 * @param {*} client 客户端实例 
 */
async function messageSnedUser(msg, userId, accessHash, title, olmsg, groupId, client) {
  let success = sendPrivateMessageToUser(client, userId, accessHash, msg)
  
  if (success) {
    console.log("群聊名称：",title)
    console.log(`私聊发送成功 - 群: ${title} 用户: ${userId}`);
    await insertMsgRecord(groupId,title,"成功",olmsg,msg,userId,accessHash)
    
  } else {
    console.error(` 私聊发送失败 - 群: ${title} 用户: ${userId}`);
    await insertMsgRecord(groupId,title,"失败",olmsg,msg,userId,accessHash)
  }

  // await sendPrivateMessageToUser(client,userId,accessHash,msg).then((res)=>{
  //   console.log("发送成功")
  // }).catch((err)=>{
  //   console.log("发送失败")
  // })
}

// (async () => {
//     // console.log(11)
//     await messageSnedUserHandler("asd","","")

//     // console.log(22)
//     // let r =  await insertKeyWrod("测试5","asdasd");
//     // console.log(r); // 正确输出 “新增成功” 或错误信息
// })();


module.exports = {
  registerHandler,
  unregisterHandler,
  getHandler,
  messageSnedUserHandler
};